package cn.hy.face.common.permission;

import cn.hy.face.common.enums.ResultCode;
import cn.hy.face.common.exception.AuthException;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpSession;
import java.util.Set;

/**
 * 权限utils
 */
public class PermissionUtils {

    /**
     * 判断是否拥有权限
     * @return
     */
    public static boolean hasPermission(HttpSession session, String schoolId, String permStr) {
        if (session == null) {
            return false;
        }
        String permissionSessionKey = PermissionConstant.PERMISSION + "_" + schoolId;
        Set<String> permissionSet = (Set<String>) session.getAttribute(permissionSessionKey);
        if (CollectionUtils.isEmpty(permissionSet)) {
            return false;
        }

        return permissionSet.contains(permStr);
    }

    /**
     * 判断是否拥有权限,没有权限抛权限异常
     * @return
     */
    public static void permissionValidate(HttpSession session, String schoolId, String permStr) {
        if (session == null) {
            throw new AuthException(ResultCode.LACK_PERMISSION, ResultCode.LACK_PERMISSION.getMessage());
        }
        String permissionSessionKey = PermissionConstant.PERMISSION + "_" + schoolId;
        Set<String> permissionSet = (Set<String>) session.getAttribute(permissionSessionKey);
        if (CollectionUtils.isEmpty(permissionSet) || !permissionSet.contains(permStr)) {
            throw new AuthException(ResultCode.LACK_PERMISSION, ResultCode.LACK_PERMISSION.getMessage());
        }
    }
}
